<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/11/22
 * Time: 14:35
 * used to create logs and insert data
 */

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Laravel\Lumen\Routing\Controller as BaseController;

class TableController extends BaseController
{
    /**
     * create logs tables
     */
    public function create_table(){
        for($i=0;$i<10;$i++){
            $sql = "CREATE TABLE IF NOT EXISTS `log_".$i."` (
  `id` int(11) NOT NULL,
  `active` varchar(255) NOT NULL,
  `pudate` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
)ENGINE=archive DEFAULT CHARSET=utf8";
            DB::statement($sql);
        }
    }

    public function delete_table(){
        for($i=0;$i<10;$i++){

        }
    }

    public function insert_data(){
        $acts = [
            '正在插入：',
            '正在删除：',
            '正在修改：',
            '正在查询：',
        ];
        for($i=0;$i<100000;$i++){
            $table = "log_".$i%10;
            $active = $acts[mt_rand(0,3)].$i;
            $pubdate = date("Y-m-d H:i:s");
            $sql = "insert into ".$table."(active,pudate) values ('{$active}','{$pubdate}')";
            DB::statement($sql);
        }
        echo "over";
    }

    /**
     * 测试事务安全性
     */
    public function strans(Request $request){
        $result = array('code'=>'100','msg'=>'success');
        $this->validate($request,[
           'uid'=>'required|numeric|exists:person,id',
           'money'=>'required|numeric'
        ]);
        $uid = intval($request->get('uid'));
        $money = $request->get('money');
        DB::beginTransaction();
        try{
            // 查询用户资金
            $uinfo = DB::table('person')->where('id',$uid)->first();
            if($uinfo->account >= $money){
                // 移出资金
                $res = DB::table('person')->where('id',$uid)->decrement('account',$money);
                if(!$res){
                    throw new \Exception('扣除用户金额失败');
                }
                sleep(60);
                // 写入提现表
                $res = DB::table('cash')->where('uid',$uid)->increment('account',$money);
                if(!$res){
                    throw new \Exception('写入提现失败');
                }
            }else{
                throw new \Exception('用户金额不足');
            }
            DB::commit();
        }catch (\Exception $e){
            DB::rollback();
            $result = array('code'=>'-100','msg'=>$e->getMessage());
        }
        echo json_encode($result);
    }

    /**
     * 强制性提取所有金额
     */
    public function money_clear(Request $request){
        $result = array('code'=>'100','msg'=>'success');
        $this->validate($request,[
            'uid' => 'required|numeric|exists:person,id'
        ]);
        $uid = intval($request->get('uid'));

    }
}